package com.app.util;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Set;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

@SuppressWarnings("unchecked")
public class JavaScriptUtil {
	
	public static void main(String[] args) throws Exception {
		String file = "CN";
		String[] script = {Constant.WebRoot+"language/zh_"+file+".js",
				Constant.WebRoot+"language/javaGetMethod.js"};
		HashMap li = (HashMap) getFileMethodDataArray(script, "getDataList", "");
		Set s = li.keySet();
		for (Object o : s) {
			String key = (String) o;
			System.out.println(key+"="+li.get(key));
		}
	}
	
	public static Object getFileMethodDataArray(String[] script, String method,
			String param) throws Exception {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("JavaScript");
		for(int i=0;i<script.length;i++){
			InputStreamReader isr = new InputStreamReader(new FileInputStream(script[i]),"UTF-8");
			engine.eval(isr);
			isr.close();
		}
		Invocable inv = (Invocable) engine;
		Object res = inv.invokeFunction(method, param); // 方法名、参数
		return res;
	}

	public static Object getScriptMethodData(String script, String method,
			String param) throws Exception {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("JavaScript");
		engine.eval(script);
		Invocable inv = (Invocable) engine;
		Object res = inv.invokeFunction(method, param); // 方法名、参数
		return res;
	}
	
	public static Object getFileMethodData(String script, String method,
			String param) throws Exception {
		ScriptEngineManager manager = new ScriptEngineManager();
		ScriptEngine engine = manager.getEngineByName("JavaScript");
		InputStreamReader isr = new InputStreamReader(new FileInputStream(script),"UTF-8");
		engine.eval(isr);
		isr.close();
		Invocable inv = (Invocable) engine;
		Object res = inv.invokeFunction(method, param); // 方法名、参数
		return res;
	}

}
